package com.intexh.quickandroid.module.chat.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.intexh.quickandroid.R;
import com.intexh.quickandroid.module.chat.ChatManager.MessageFactory;
import com.intexh.quickandroid.module.chat.adapter.AppChatAdapter;
import com.intexh.quickandroid.module.chat.bean.ChatMessage;
import com.intexh.quickandroid.module.chat.bean.ChatSession;
import com.intexh.quickandroid.module.chat.event.NewMessageReceivedEvent;
import com.intexh.quickandroid.module.chat.ui.face.EmojiFactory;
import com.intexh.quickandroid.module.chat.ui.face.EmojiPageAdapter;
import com.intexh.quickandroid.module.chat.ui.voiceRecorder.RecorderVoiceView;
import com.intexh.quickandroid.utils.GsonUtils;
import com.intexh.quickandroid.utils.InputMethodUtils;
import com.intexh.quickandroid.utils.LogCatUtil;
import com.intexh.quickandroid.utils.Settings;
import com.intexh.quickandroid.utils.UIUtil;
import com.intexh.quickandroid.utils.ValidateUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Frank on 2017/5/2.
 */

public class AppChatFragment extends Fragment implements View.OnClickListener{

    private ImageView backIv,phoneIv,recordIv,emojiIv,expandIv,groupMemberIv;
    private ViewPager emojiViewPager;
    private FrameLayout actionLayout;
    private ListView messageListView;
    private EditText chatInputEditText;
    private TextView sendTv;
    private TextView nameTv;
    private ChatSession mChatSession;

    private List<ChatMessage> mChatMessageList=new ArrayList<>();
    private AppChatAdapter mChatAdapter;
    private Context mContext;
    private boolean isSelectEmoji;
    private boolean isSelectRecord;
    private boolean moreIsShow;
    private LinearLayout picture_llt;
    private LinearLayout emoji_llt;
    private LinearLayout location_llt,rootView;
    private RecorderVoiceView recorderVoiceViewLayout;
    private View thisView;
    private RelativeLayout goods_rlt;
    private LinearLayout photoSelectLayout,takePhotoLayout,assistLayout,videoCall_layout,voiceCall_layout;
    private TextView group_list_tv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        thisView = inflater.inflate(R.layout.fragment_app_chat, container, false);
        mContext = container.getContext();
        initExtra();
        initView(thisView);
        initData(thisView);
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return thisView;
    }

    private void initData(final View view) {
        if(mChatSession.getIsGroup()) {
            nameTv.setText(mChatSession.getGroup_name());
        }else {
            nameTv.setText(mChatSession.getName());
        }
        mChatAdapter=new AppChatAdapter(mContext,mChatMessageList);
        messageListView.setAdapter(mChatAdapter);
        mChatMessageList = ChatMessage.getAll(mChatSession.getSessionId());
        initEmojiPage(view);
        initVoiceRecord();
        messageListView.post(() -> {
            mChatAdapter.setData(mChatMessageList);
            messageListView.setSelection(mChatMessageList.size() - 1);
        });
    }

    private void initExtra() {
        Bundle bundle = getArguments();
        mChatSession = ChatSession.getSession(bundle.getString(AppChatActivity.SESSION_ID));
        if (mChatSession == null) {
            mChatSession = new ChatSession();
        }
        mChatSession.setSessionId(bundle.getString(AppChatActivity.SESSION_ID));
        mChatSession.setIsGroup(bundle.getBoolean(AppChatActivity.IS_GROUP));
        mChatSession.setUid(bundle.getString(AppChatActivity.UID));
        mChatSession.setTime(System.currentTimeMillis());
        mChatSession.setAvatar(bundle.getString(AppChatActivity.AVATAR));
        mChatSession.setName(bundle.getString(AppChatActivity.NICK_NAME));
        mChatSession.setNotReadCount(0); //未读条数
        if(bundle.getBoolean(AppChatActivity.IS_GROUP)) {
            mChatSession.setGroup_name(bundle.getString(AppChatActivity.GROUP_NAME));
            mChatSession.setGroup_avatar(bundle.getString(AppChatActivity.GROUP_AVATAR));
            mChatSession.setGroup_id(bundle.getString(AppChatActivity.GROUP_ID));
        }
        mChatSession.save();
    }


    private void initView(final View view) {

        rootView = view.findViewById(R.id.root_view);
//        //监听软键盘隐藏显示
//        //监听软键盘弹起和隐藏
//        rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
//            int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight();
//            if (heightDiff > UIUtil.dp2px(getContext(), 200)) { //显示
//                isSoftInputVisable = true ;
//                assistLayout.setVisibility(View.GONE);
//            }else {
//                isSoftInputVisable = false ;
//                if(isExpand) {
//                    assistLayout.setVisibility(View.VISIBLE);
//                }
//            }
//        });

        recordIv=  view.findViewById(R.id.recordIv);
        backIv=  view.findViewById(R.id.backIv);
        nameTv=  view.findViewById(R.id.nameTv);
        recordIv=  view.findViewById(R.id.recordIv);
        chatInputEditText=  view.findViewById(R.id.chatInputEditText);
        messageListView=  view.findViewById(R.id.messageListView);
        emojiViewPager= view.findViewById(R.id.emojiViewPager);
        actionLayout=  view.findViewById(R.id.actionLayout);
        groupMemberIv=  view.findViewById(R.id.group_member_img);
        group_list_tv=  view.findViewById(R.id.group_list_tv);
        recorderVoiceViewLayout= view.findViewById(R.id.recorderVoiceViewLayout);
        photoSelectLayout = view.findViewById(R.id.photo_select_layout);
        takePhotoLayout = view.findViewById(R.id.take_photo_layout);
        videoCall_layout = view.findViewById(R.id.videoCall_layout);
        voiceCall_layout = view.findViewById(R.id.voiceCall_layout);
        assistLayout = view.findViewById(R.id.bottom_assist_layout);
        emojiIv=  view.findViewById(R.id.emotion_img);
        expandIv=  view.findViewById(R.id.expand_img);

        //录音
        recordIv=  view.findViewById(R.id.recordIv);
        actionLayout=  view.findViewById(com.intexh.quickandroid.R.id.actionLayout);

        Bundle bundle = getArguments();
        boolean isGroup = bundle.getBoolean(AppChatActivity.IS_GROUP);
        if(isGroup) { //群聊
//            groupMemberIv.setVisibility(View.VISIBLE);
            group_list_tv.setVisibility(View.VISIBLE);
            videoCall_layout.setVisibility(View.GONE);
        }else {
//            groupMemberIv.setVisibility(View.GONE);
            group_list_tv.setVisibility(View.GONE);
            videoCall_layout.setVisibility(View.GONE);
        }

        groupMemberIv.setOnClickListener(this);
        group_list_tv.setOnClickListener(this);
        expandIv.setOnClickListener(this);
        backIv.setOnClickListener(this);
        recordIv.setOnClickListener(this);
        photoSelectLayout.setOnClickListener(this);
        takePhotoLayout.setOnClickListener(this);
        voiceCall_layout.setOnClickListener(this);
        videoCall_layout.setOnClickListener(this);
        emojiIv.setOnClickListener(this);

        chatInputEditText.setOnClickListener(this);
        chatInputEditText.setOnEditorActionListener((v, actionId, event) -> { //发送消息
            if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                if (TextUtils.isEmpty(chatInputEditText.getText().toString())) {
                    Toast.makeText(getActivity(), "不能发送空消息", Toast.LENGTH_SHORT).show();
                }else {
                    sendText(chatInputEditText.getText().toString());
                    InputMethodUtils.hideSoftInput(getActivity());
                    chatInputEditText.setText("");
                }
                return true;
            } else {
                return false;
            }
        });
        messageListView.setOnTouchListener((v, event) -> {
            actionLayout.setVisibility(View.GONE);
            assistLayout.setVisibility(View.GONE);
            recorderVoiceViewLayout.setVisibility(View.GONE);
            InputMethodUtils.hideSoftInput(view);
            return false;
        });
    }

    private void initEmojiPage(View view) {
        final ViewPager emojiViewPager = view.findViewById(R.id.emojiViewPager);
        emojiViewPager.setOffscreenPageLimit(0);
        EmojiPageAdapter adapter = new EmojiPageAdapter(mContext,
                emojiCode -> {
                    //删除表情
                    if (EmojiPageAdapter.DELETE_CODE.equals(emojiCode)) {
                        int start =chatInputEditText.getSelectionStart();
                        SpannableStringBuilder ssb = new SpannableStringBuilder(chatInputEditText.getText());
                        ImageSpan[] spans = ssb.getSpans(0,chatInputEditText.getText().length(), ImageSpan.class);
                        boolean deleteSuccess = false;
                        for (ImageSpan span : spans) {
                            int spanStartStart = ssb.getSpanStart(span);
                            int spanStartEnd = ssb.getSpanEnd(span);
                            if (spanStartEnd == start) {
                                chatInputEditText.getText().delete(spanStartStart, spanStartEnd);
                                deleteSuccess = true;
                                break;
                            }
                        }
                        if (!deleteSuccess) {
                            if (start > 0) {
                                chatInputEditText.getText().delete(start - 1, start);
                            }
                        }
                    } else if (emojiCode != null) {
                        int start = chatInputEditText.getSelectionStart();
                        String text = EmojiFactory.codePointToString(emojiCode);
                        chatInputEditText.getText().insert(start, EmojiFactory.convertToEmojiText(mContext, text));
                    }
                });
        adapter.setVerticalSpacing((Settings.getInt(Settings.KEYBOARD_HEIGHT,
                UIUtil.dp2px(mContext, 216)) - UIUtil.dp2px(mContext, 32 * 5)) / 5);
        adapter.notifyDataSetChanged();
        emojiViewPager.setAdapter(adapter);
        emojiViewPager.setCurrentItem(0);
        adapter.setVerticalSpacing((getContainerHeight() - UIUtil.dp2px(mContext, 32 * 5)) / 5);
    }


    private int getContainerHeight(){
        int defaultKeyboardHeight = UIUtil.dp2px(mContext, 216);
        int pickerContainerHeight = Settings.getInt(Settings.KEYBOARD_HEIGHT,defaultKeyboardHeight);
        int showingWindowHeight = Settings.getInt(Settings.SHOWING_WINDOW_HEIGHT, -1);
        if ((showingWindowHeight * 2 / 5) > pickerContainerHeight) {
            pickerContainerHeight = showingWindowHeight * 2 / 5;
        }
        return pickerContainerHeight;
    }

    private void initVoiceRecord() {
        //语音发送监听
        recorderVoiceViewLayout.setVoiceRecorderCallback(new RecorderVoiceView.VoiceRecorderCallback() {
            @Override
            public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                sendVoice(voiceFilePath, voiceTimeLength * 1000);
            }
        });

    }

    private void sendText(String text) {
        ChatMessage chatMessage = MessageFactory.getInstance()
                .createTextMessage(text);
        sendMessage(chatMessage);
    }

    private void sendVoice(String localUrl, int length) {
        ChatMessage chatMessage = MessageFactory.getInstance()
                .createVoiceMessage(localUrl, length);
        sendMessage(chatMessage);
    }

    private void sendImages(List<LocalMedia> imageList) { //批量发送图片
        for(LocalMedia media : imageList){
            String path = media.getPath();  //去压缩的图片
            ChatMessage chatMessage = MessageFactory.getInstance()
                    .createImageMessage(path);
            sendMessage(chatMessage);
        }
    }


    /**
     *
     * @param chatMessage
     */
    private void sendMessage(ChatMessage chatMessage){
        if(mChatSession.getIsGroup()) {
            chatMessage.setGroup_avatar(mChatSession.getGroup_avatar());
            chatMessage.setGroup_name(mChatSession.getGroup_name());
            chatMessage.setGroup_id(mChatSession.getGroup_id());
        }
        chatMessage.setEasemob_id(mChatSession.getSessionId());
        chatMessage.setIs_group(mChatSession.getIsGroup());
        chatMessage.save();
        mChatSession.setCreateTime(System.currentTimeMillis());
        mChatSession.setLastMessage(GsonUtils.serializedToJson(chatMessage));
        mChatSession.save();
        mChatMessageList.add(chatMessage);
        messageListView.setSelection(mChatMessageList.size()-1);
//        mChatAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        Bundle bundle = getArguments();
        switch (v.getId()){
            case R.id.backIv:
                getActivity().finish();
                break;
            case R.id.recordIv:
                AndPermission.with(mContext)
                        .requestCode(101)
                        .permission(Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE)
                        .rationale((requestCode, rationale) -> {
                            // 此对话框可以自定义，调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(mContext, rationale).show();
                        })
                        .callback(new PermissionListener() {
                            @Override
                            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                recorderVoiceViewLayout.setVisibility(View.VISIBLE);
                                actionLayout.setVisibility(View.GONE);
                                assistLayout.setVisibility(View.GONE);
                                InputMethodUtils.hideSoftInput(getActivity());
                            }

                            @Override
                            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                                if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                                    AndPermission.defaultSettingDialog(mContext).show();
                                }
                            }
                        }).start();
                break;
            case R.id.group_member_img: //查看聊天好友信息
               /* LogCatUtil.e("gaohua","uid11:"+bundle.getString(AppChatActivity.CLASS_ID));
                Intent intent = new Intent(getContext(),ClassStudentListActivity.class) ;
                intent.putExtra("class_id",bundle.getString(AppChatActivity.CLASS_ID)) ;
                startActivity(intent);*/
                break;
            case R.id.group_list_tv: //查看群成员
                Intent intent  = new Intent(mContext,GroupListActivity.class);
                LogCatUtil.e("frank",",mChatSession.getGroup_id()="+mChatSession.getGroup_id());
                intent.putExtra("id",mChatSession.getGroup_id());
                startActivity(intent);
                break;
            case R.id.chatInputEditText:
                assistLayout.setVisibility(View.GONE);
                actionLayout.setVisibility(View.GONE);
                break;
            case R.id.emotion_img:
                assistLayout.setVisibility(View.GONE);
                actionLayout.setVisibility(actionLayout.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);
                emojiViewPager.setVisibility(View.VISIBLE);
                InputMethodUtils.hideSoftInput(getActivity());
                break;
            case R.id.photo_select_layout: //选择图片
                showPictureSelecter();
                break;
            case R.id.take_photo_layout: //拍照
                showTakePhoto();
                break;
            case R.id.videoCall_layout: //视频通话
                AndPermission.with(mContext)
                        .requestCode(101)
                        .permission(Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                        .rationale((requestCode, rationale) -> {
                            // 此对话框可以自定义，调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(mContext, rationale).show();
                        })
                        .callback(new PermissionListener() {
                            @Override
                            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                startVideoCall();
                            }

                            @Override
                            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                                if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                                    AndPermission.defaultSettingDialog(mContext).show();
                                }
                            }
                        }).start();
                break;
            case R.id.voiceCall_layout: //语音通话
                AndPermission.with(mContext)
                        .requestCode(102)
                        .permission(Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                        .rationale((requestCode, rationale) -> {
                            // 此对话框可以自定义，调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(mContext, rationale).show();
                        })
                        .callback(new PermissionListener() {
                            @Override
                            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                startVoiceCall();
                            }

                            @Override
                            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                                if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                                    AndPermission.defaultSettingDialog(mContext).show();
                                }
                            }
                        }).start();
                break;
            case R.id.expand_img: //展开，隐藏
                if(assistLayout.getVisibility()==View.GONE) {
                    InputMethodUtils.hideSoftInput(getActivity());
                    assistLayout.setVisibility(View.VISIBLE);
                    emojiViewPager.setVisibility(View.GONE);
                }else {
                    assistLayout.setVisibility(View.GONE);
                    actionLayout.setVisibility(View.GONE);
                }

                break;
            /*case R.id.sendTv:
                if(!ValidateUtils.isValidate(chatInputEditText.getText().toString())){
                    Toast.makeText(getActivity(),"不能发送空消息",Toast.LENGTH_SHORT).show();
                    return;
                }
                sendText(chatInputEditText.getText().toString());
                chatInputEditText.setText("");
                break;*/
        }
    }

    /**
     * make a voice call
     */
    protected void startVoiceCall() {
//        if (!EMClient.getInstance().isConnected()) {
//            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
//        } else {
//            startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", mChatSession.getSessionId())
//                    .putExtra("isComingCall", false));
//            // voiceCallBtn.setEnabled(false);
//            assistLayout.setVisibility(View.GONE);
//        }
    }

    /**
     * make a video call
     */
    protected void startVideoCall() {
//        if (!EMClient.getInstance().isConnected())
//            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
//        else {
//            startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", mChatSession.getSessionId())
//                    .putExtra("isComingCall", false));
//            // videoCallBtn.setEnabled(false);
//            assistLayout.setVisibility(View.GONE);
//        }
    }

    private void showTakePhoto() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void showPictureSelecter() {
        // 进入相册
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageSpanCount(3)
                .selectionMode(PictureConfig.MULTIPLE)
                .isCamera(true)
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
                    if(ValidateUtils.isValidate(localMedias)){
                        sendImages(localMedias);
                    }
                    break;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(final NewMessageReceivedEvent event){ //接收到新消息
        final ChatMessage message= event.getChatMessage();
        if (message.getEasemob_id().equals(mChatSession.getSessionId())){
            mChatMessageList.add(message);
            mChatAdapter.notifyDataSetChanged();
            messageListView.setSelection(mChatMessageList.size()-1);
            mChatSession.setNotReadCount(0);
            mChatSession.save();
        }
    }

}
